const express = require("express");
const router = express.Router();
const fs = require("fs");
const multer = require("multer");
const upload = multer();

router.get("/dataDownload", (req, res) => {
  fs.readFile(`./static/${req.query.fileName}`, function (err, result) {
    if (err) {
      console.log("is warning: " + err);
      res.send({ status: 202, message: "文件不存在" });
    } else {
      res.send(result);
    }
  });
});

router.get("/dataDownload/filesName", (req, res) => {
  fs.readdir("./static", (err, files) => {
    if (err) {
      res.send({ status: 202, message: err });
      return console.log(err);
    }
    console.log("文件列表读取成功");
    res.send({ status: 200, data: files });
  });
});

// 处理第一次握手
// router.options("/dataDownload/uploadFiles", (req, res, next) => {
//   res.status(200).end();
// });

router.post("/dataDownload/uploadFiles", upload.any(), (req, res) => {
  console.log(req.files[0]);
  
  fs.writeFile(`./static/${req.files[0].originalname}`, req.files[0].buffer, (err) => {
    if (err) {
      console.log(err);
    }
  });
  res.status(200).end();
});

module.exports = router;
